<script setup lang="ts">
import {shopTypes, supplierOpts} from "@/utils/status";
import {supplierFields} from "@/utils/field";
import {createSupplier, getSupplierInit, supplierDetail, SupplierForm, updateSupplier,} from "@/api/supplier";
import {basePriceForm} from "@/api/shop/types";

defineOptions({
  name: "SupplierEdit",
  inheritAttrs: false,
});

const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  supplierId: {
    type: Number,
    default: null,
  },
});

const steps = ref<String[]>([
  "基础信息",
  "配送信息",
  "店铺营业信息",
  "资质证照",
]);

const objFormRef = ref(ElForm);
const loading = ref(false);
const ids = ref<number[]>([]);

const statusOptions = supplierOpts();
const shopType = shopTypes();
const price_groups = ref<basePriceForm[]>([]);
const priceForm = reactive<basePriceForm>({
  min: 1,
  max: undefined,
  total: undefined
})

const originData = (): SupplierForm => ({
  id: undefined,
  type: 0,
  title: undefined,
  name: undefined,
  park_id: undefined,
  supplier_id: undefined,
  distrute_rank: undefined,
  service_money: undefined,
  deliver_type: 1,
  is_open: 1,
  prepare_time: undefined,
  deliver_time: undefined,
  contact_name: undefined,
  contact_phone: undefined,
  shipping_fee: undefined,
  delivery_phone: undefined,
  address: undefined,
  ava_price: undefined,
  bag_price: undefined,
  min_money: undefined,
  thumb: undefined,
  banner: undefined,
  description: undefined,
  store_time: undefined,
  location: undefined,
  food_license: undefined,
  business_license: undefined,
  order_end_time: undefined,
  base_shipping_price: undefined,
  stock_cal_type: 0,
  status: 1,
  enable_profit_share: 0,
  role_id: [0],
  is_label: 0,
  sort: 20,
  accept_order_type: 0,
  is_remark: 0,
})

const formData = reactive(originData());

// 当前位置
const stepActive = ref(0);
const btnActive = ref(true);
const dialog_title = ref("新增店铺");
let modelFields = supplierFields();

watch(
  () => props.supplierId,
  (newVal) => {
    if (newVal) {
      loading.value = true;
      dialog_title.value = "修改商铺";
      supplierDetail(newVal).then(({data}) => {
        Object.assign(formData, data);
        if (formData.base_shipping_price && formData.base_shipping_price.length) {
          Object.assign(price_groups.value, formData.base_shipping_price)
        }
        changeCheckbox('role_id');
      }).then(() => {
      }).finally(() => {
        loading.value = false;
        btnActive.value = true;
      })
    }
  }
);

/**
 * 多图上传成功
 * @param res
 */
function uploadMuliSuccess(res: any) {
  let pictureIds = reactive<Number[]>([]);
  res.forEach((item: any) => {
    pictureIds.push(item.id);
  });

  formData.picture_ids = pictureIds || [];
}

const rules = reactive([
  {
    park_id: [{required: true, message: "请选择所在园区", trigger: "blur"}],
    supplier_id: [{required: true, message: "请选择所属商户", trigger: "blur"}],
    title: [{required: true, message: "请输入名称", trigger: "blur"}],
    name: [{required: true, message: "英文简称必填，用于生成商品编号", trigger: "blur"}],
    contact_name: [{required: true, message: "请输入联系人", trigger: "blur"}],
    role_id: [{required: true, message: "访问权限", trigger: "blur"}],
    status: [{required: true, message: "请选择状态", trigger: "blur"}],
  },
  {
    delivery_phone: [{required: true, message: "配送员联系方式必填", trigger: "blur"}],
    base_shipping_price: [{required: true, message: "基础费用必填", trigger: "blur"}],
  },

]);

/** 保存提交 */
function handleSubmit() {

  if (stepActive.value == 1) {
    formData.base_shipping_price = price_groups.value || [];
  }

  objFormRef.value.validate((valid: any) => {
    if (valid) {
      if (!btnActive.value)
        return;

      btnActive.value = false
      loading.value = true;
      formData.step = stepActive.value || 0;

      const roleId = formData.id;
      if (roleId) {
        updateSupplier(roleId, formData)
          .then((res) => {
            if (stepActive.value++ >= 3) {
              closeDialog()
              return;
            }
          })
          .finally(() => {
            loading.value = false;
            btnActive.value = true;
          })
      } else {
        createSupplier(formData)
          .then((data) => {
            Object.assign(formData, data.data || {})
            stepActive.value = 1;
          }).catch(errmsg => {
        })
          .finally(() => {
            loading.value = false
            btnActive.value = true;
          });
      }
    }
  });
}

/**
 * 上一步
 */
function prev() {
  if (stepActive.value > 0) {
    stepActive.value--;
  }
}

const emit = defineEmits(["close"]);

/** 关闭表单弹窗 */
function closeDialog() {
  resetSupplierEditForm();
  stepActive.value = 0;
  roleCheck.value = false;
  emit("close");
}

/** 重置表单 */
function resetSupplierEditForm() {
  objFormRef.value.resetFields();
  objFormRef.value.clearValidate();
  Object.assign(formData, originData())
  price_groups.value = []

  Object.assign(priceForm, {
    min: 1,
    max: undefined,
    total: undefined
  })
}

function uploadSucess(res: any) {
  formData[res.name] = res.value || ''
}

onMounted(() => {
  getSupplierInit().then(({data}) => {
    modelFields[0].park_id.options = data.parks || [];
    modelFields[0].supplier_id.options = data.shops || [];
  })
})

function addSpec() {
  const min = parseInt(priceForm.min || 0);
  const max = parseInt(priceForm.max || 0);
  const total = priceForm.total || 0;

  if (min < 0) {
    return ElMessage.error("最小数量必填")
  }
  if (max <= 0) {
    return ElMessage.error("最大数量必填")
  }

  if (min > max) {
    return ElMessage.error("最大必须大于最小数量")
  }

  if (total < 0) {
    return ElMessage.error("金额必填")
  }

  price_groups.value.push({
    min: min,
    max: max,
    total: total
  })

  Object.assign(priceForm, {
    min: max,
    max: undefined,
    total: undefined
  })

}

function removeSpec(idx: any) {
  if (!idx && idx != 0)
    return;
  price_groups.value.splice(idx, 1);
}

const roleCheck = ref(false);

/**
 * 选择访问权限
 * @param key
 */
function changeCheckbox(key: string) {
  if (key != 'role_id') return false;

  if (formData['role_id']!.indexOf(0) != -1) {
    formData['role_id'] = [0]
    roleCheck.value = true;
  } else {
    roleCheck.value = false;
  }
}

</script>

<!-- 编辑表单弹窗 -->
<template>
  <el-dialog v-model="props.visible" :title="dialog_title" width="720px" @close="closeDialog">
    <el-steps :active="stepActive" style="max-width: 560px; margin: 30px auto" finish-status="success">
      <el-step :title="item" v-for="item in steps"/>
    </el-steps>
    <el-form ref="objFormRef" :model="formData" :rules="rules[stepActive]" label-width="160px">
      <template v-for="(field, fk) in modelFields[stepActive]">
        <el-form-item :label="field.title" :prop="fk.toString()" :key="fk" :class="field.class"
                      v-if="!field.relateKey || (field.relateKey  && formData[field.relateKey] == field.relateVal)">

          <el-radio-group v-model="formData[fk]" v-if="field.type == 'radio'">
            <el-radio :label="Number(ok)" v-for="(op, ok) in field.options" :key="ok">{{ op }}</el-radio>
          </el-radio-group>

          <el-select v-model="formData[fk]" v-else-if="field.type == 'select'">
            <el-option :label="op.title || ''" v-for="op in field.options" :value="Number(op.id)"
                       v-if="field.range_key"/>
            <el-option :label="Number(op) || ''" v-for="(op, ok) in field.options" :value="Number(ok)" v-else/>
          </el-select>

          <el-checkbox-group v-model="formData[fk]" v-else-if="field.type == 'checkbox'"
                             @change="changeCheckbox(fk + '')">
            <el-checkbox :label="Number(ok)" v-for="(op, ok) in field.options" :key="ok"
                         :disabled="(roleCheck && ok > 0) ?true: false"
            >{{ op }}
            </el-checkbox>
          </el-checkbox-group>

          <div v-else-if="field.type == 'base_price'">
            <div class="spec-group">
              <div class="spec-group-item" v-for="(p, pk) in price_groups">
                <el-input class="num" v-model="p.min" placeholder="最小" clearable/>
                <el-text class="tip">~</el-text>
                <el-input v-model="p.max" class="num" placeholder="最大" clearable/>
                <el-text class="tip">件</el-text>
                <div class="total">
                  <el-input v-model="p.total" class="tt" placeholder="费用" clearable/>
                  <el-icon class="t-op" size="20" @click="removeSpec(pk)" style="color: red;">
                    <RemoveFilled/>
                  </el-icon>
                </div>
              </div>
              <div class="spec-group-item">
                <el-input class="num" v-model="priceForm.min" placeholder="最小" clearable/>
                <el-text class="tip">~</el-text>
                <el-input v-model="priceForm.max" class="num" placeholder="最大" clearable/>
                <el-text class="tip">件</el-text>
                <div class="total">
                  <el-input v-model="priceForm.total" class="tt" placeholder="费用" clearable/>
                  <!--                  <el-button @click="addSpec()"></el-button>-->
                  <el-icon class="t-op" size="20" @click="addSpec()">
                    <CirclePlusFilled/>
                  </el-icon>
                </div>
              </div>

            </div>
          </div>

          <single-upload :modelValue="formData[fk]" :fkey="String(fk)" @upload-sucess="uploadSucess"
                         v-else-if="field.type == 'image'"/>

          <multi-upload v-model="formData[fk]" :fkey="String(fk)" @uploadMuliSuccess="uploadMuliSuccess"
                        v-else-if="field.type == 'mutiImage'"/>

          <el-time-picker v-model="formData[fk]" :value-format="field.format" is-range range-separator="至"
                          start-placeholder="起始时间" end-placeholder="结束时间" v-else-if="field.type == 'timerange'"/>

          <el-input :type="field.type || 'text'" v-model="formData[fk]" :placeholder="'请输入' + field.title" v-else/>
          <!--          <el-text style="color: #999999;margin-left: 10rpx;display: inline-block;">分钟</el-text>-->
        </el-form-item>

      </template>

      <div class="clear"></div>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button type="default" @click="prev" v-if="stepActive > 0 && stepActive < 4">上一步</el-button>
        <el-button type="primary" @click="handleSubmit">{{ stepActive == 3 ? '保存' : '下一步' }}</el-button>
        <!--        <el-button @click="closeDialog" type="default">取 消</el-button>-->
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>

.spec-group .spec-group-item {
  margin-bottom: 10px;
}

.spec-group .spec-group-item .num {
  width: 100px;
}

.spec-group .spec-group-item .tip {
  margin: 0px 10px;
  display: inline-block;
  color: #666666;
}

.spec-group .spec-group-item .total {
  position: relative;
  display: inline-block;
  margin-left: 15px;
}

.spec-group .spec-group-item .total .unit {
  position: absolute;
  top: 10px;
}

.spec-group .spec-group-item .total .tt {
  width: 160px;
}

.spec-group .spec-group-item .total .t-op {
  margin: 5px 10px;
  position: relative;
  vertical-align: middle;
  color: #239439;
}

</style>
